package com.fyt.service.serviceImp;

import com.fyt.result.R;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.fyt.service.DiscoveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.core.env.Environment;
import org.springframework.http.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ：fyt
 * @Date: 2024/4/13 18:15
 */
public class DiscoveryOpenApiServiceImpl implements DiscoveryService {

    @Autowired
    private Environment environment;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${serverAddr.ip}")
    private String nacosIp;
    @Value("${serverAddr.port}")
    private Integer nacosPort;
    @Value("${serverAddr.openApi}")
    private String nacosOpenApi;
    @Value("${localAddr.serviceName}")
    private String serviceName;
    private static final String URI = "http://";
    private static final String SERVER_PORT = "server.port";
    private static final String AND = "&";
    private static final String QUESTION = "?";
    private static final String COLON = ":";
    private static final String EQ = "=";

    @Override
    public R registerNacosInstance() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 实例信息
        Instance instance = new Instance();
        // 参数解析
        HashMap<String, Object> map = new HashMap<>();
        try {
            // 设置实例参数
            String localHost = InetAddress.getLocalHost().getHostAddress();
            instance.setIp(localHost);
            instance.setPort(Integer.parseInt(environment.getProperty(SERVER_PORT)));
            instance.setServiceName(serviceName);
            map.putAll(BeanMap.create(instance));

            // 删除null参数
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                if (ObjectUtils.isEmpty(entry.getValue())) {
                    entries.remove(entry.getKey());
                }
            }

            // 参数拼接
            String url = URI + nacosIp + COLON + nacosPort + nacosOpenApi + QUESTION;
            for (Map.Entry<String, Object> entry : entries) {
                url += entry.getKey() + EQ + entry.getValue() + AND;
            }

            // 设置请求头  发送请求
            HttpEntity<Instance> entity = new HttpEntity<>(instance, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
            // 返回结果
            if (HttpStatus.OK == response.getStatusCode()) {
                return R.Success();
            }
            return R.Failed(response.getStatusCodeValue(), response.getStatusCode().toString());
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return R.Failed("获取本机ip失败");
        }

    }
}
